import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from pandas import DataFrame
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

plt.rcParams['font.sans-serif']=['simhei']#使用配置文件定义plt生成图形

iris=load_iris()
#print(iris.DESCR)

iris_data=iris.data
feature_names=iris.feature_names
iris_target=iris.target

iris_target.shape = (150,1)
iris_all=np.hstack((iris_data,iris_target))

iris_data_df=DataFrame(iris_data,columns=feature_names)
iris_target_df=DataFrame(iris_target,columns=['target'])
iris_data_all_df = DataFrame(iris_all,columns= feature_names + ['target'])

print(iris_data_all_df.sample(5))
print(iris_data_all_df.info())

#数据范围
sns.boxplot(data=iris_data)
plt.title("数据的范围")
plt.show()

#总览
plt.plot(iris_data_df)
plt.legend(feature_names)
plt.title("数据总览")
plt.show()

#相关性
sns.pairplot(iris_data_all_df,vars=iris_data_all_df.columns[:4],hue='target',size=3,kind="reg")
plt.title('数据相关性')
plt.show()

#变量之间的关系
Corr_Mat=iris_data_all_df.corr()
Mat_img=plt.matshow(Corr_Mat,cmap=plt.cm.winter_r)#包含蓝和绿的阴影色
plt.colorbar(Mat_img,ticks=[-1,0,1])#颜色条
plt.title("变量关系")
plt.show()

pca=PCA(n_components=2)
pca_2a=pca.fit_transform(iris_data_df)
print("各个主成分的方差值占总方差值的比例：")
print(pca.explained_variance_ratio_)

#降维
plt.scatter(pca_2a[:,0],pca_2a[:,1],c=np.array(iris_target_df),alpha=0.8,cmap=plt.cm.winter)
plt.title("降维")
plt.show()

#数据分析
X_train,X_text,y_train,y_text=train_test_split(iris_data_df,iris_target_df,test_size=0.3)
clf=SVC()
clf.fit(X_train,y_train)
predictions=clf.predict(X_text)
print("分类准确性")
print(accuracy_score(y_text,predictions))